var express = require('express');
var path = require('path')
var mathjax = require('mathjax-node/lib/mj-page.js')
var markdown = require('markdown-it')
var jsdom = require("jsdom").jsdom;
var fs = require('fs')
var queryString = require('querystring')
var bodyParser = require('body-parser');
var cheerio = require('cheerio')
var JsDiff = require('diff')
var mongoose = require('mongoose')
var Article = require('./model/article.js')
mongoose.connect('mongodb://localhost/myblog')
mongoose.Promise = require('bluebird')
// var JSON = require('JSON')
var md = markdown({
  html: true,
  linkify: true,
  typographer: true,
  highlight: true,
})
  .use(require('markdown-it-mathjax'))
  .use(require('markdown-it-lazy-headers'))
  .use(require('markdown-it-footnote'))
  .use(require('markdown-it-task-lists'))
  .use(require('markdown-it-highlightjs'), {
    auto: true,
    code: true
  })
  .use(require('markdown-it-github-toc'), {
    anchorLinkSymbol: '',
  })
  .use(require('markdown-it-deflist'))

var app = express()
var fileData = ''
app.set('view engine', 'jade')
app.set('views', 'views')
app.use(express.static(path.join(__dirname, 'resources')))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}))

fs.readFile('md.md', 'utf8', function(err, data) {
  if (err) {
    throw err
  }else {
    fileData = data + '\n[toc]'
  }
})

function appendStyles(html) {
  var $ = cheerio.load(html)
  $('table').addClass('table table-striped table-bordered')
  $('img').addClass('img')
  return $.html()
}
function createMenu(html) {
  var $ = cheerio.load(html)
  var menu = $('ul.markdownIt-TOC').last()
  $($('ul.markdownIt-TOC').last()).remove()

  var title = menu.find('li > a ').first().text()
  return {
    html: $.html(),
    menu: menu.html(),
    title: title,
  }
}
function parseMarkdown(text) {
    text += '\n[toc]'
    var r = md.render(text);
    var f = appendStyles(r)
    var g = createMenu(f)
  return g;
}


//Route Block
app.get('/', function(req, res){
  //找到数据库中最新的那片文章
    var h = parseMarkdown(fileData)
      res.render('articles/articles.jade', 
      {
        title: 'CmST0us`',
        article: {
          title: h.title,
          context: {
            md: '#dafsdfasdfsdaf\n',
            html: h.html,
            menu: h.menu,
            author: 'CmST0us',
          }
        }
      }
      )
});

app.get('/editor/:id', function(req, res) {
  Article.findById(req.params.id, function(err, article) {
    if (err) {
      console.log('内部错误: ' + err)
    }else{
      res.render('admin/editor.jade', {article: article})
    }
  })
  // a.save()
  // res.render('admin/editor.jade', {
  //   title: 'CmST0us`',
  //   article: a
  // })
})
app.get('/editor/', function(req, res) {
  res.render('admin/editor.jade', {article: {
  title: '',
  container: {
    md: '',
    html: '',
    menu: '',
    author: '',
  }}
  })
  // a.save()
  // res.render('admin/editor.jade', {
  //   title: 'CmST0us`',
  //   article: a
  // })
})

app.post('/ajax/mdLive/saveArticle', function (req, res) {
  var articleIdRaw = JSON.stringify(req.body.id)
  var articleIdURIWarp = new Buffer(articleIdRaw, 'base64').toString()
  var articleId = decodeURIComponent(articleIdURIWarp) 
  var mdTextURIWarp = new Buffer(req.body.text, 'base64').toString()
  var mdText = decodeURIComponent(mdTextURIWarp)
  var mdHtml = parseMarkdown(mdText)
  var a = new Article({
    _id: articleId,
    title: mdHtml.title,
    container: {
      md: mdText,
      html: mdHtml.html,
      menu: mdHtml.menu,
      author: 'CmST0us',
    }
  })

  Article.findById(articleId, function(err, obj) {
    if (err) {
      //查询出错
      res.send({return: '失败: 数据库读取错误'})
    }else{
      if (obj == null){
        //找不到
        a.save(function(err) {
          if (err) {
            res.send({return: '失败: 数据库储存出错!'})
          }else{
            res.send({return: '成功'})
          }
        })
      }else{
        //找到了
        Article.findByIdAndUpdate(articleId, {$set: a}, function(err) {
          if (err) {
            res.send({return: '失败: 数据库储存出错!'})
          }else{
            res.send({return: '成功'})
          }
        })
      }
    }
  })   
  
  }
)

app.listen(3000);

// app.post('/ajax/mdLive/update', function (req, res) {
//   var articleIdRaw = JSON.stringify(req.body.id)
//   var articleId = new Buffer(articleIdRaw, 'base64').toString()

//       var mdLiveLastValue = req.container.html
//       console.log(mdLiveLastValue)
//     // var mdLiveLastTime = ''
//       var diffRaw = JSON.stringify(req.body.update)
//       var diff = new Buffer(diffRaw, 'base64').toString()
//       var mdLiveNewValue = JsDiff.applyPatch(mdLiveLastValue, diff)
//       var newMdObj = parseMarkdown(mdLiveNewValue)
      
//       Article.findByIdAndUpdate(articleId, {$set: {
//         title: newMdObj.title,
//         container:{
//           html: newMdObj.html,
//           menu: newMdObj.menu,
//         },
//       }})

//       reass.send({res: newMdObj.html})
//   }
//     // mdLiveLastValue = mdLiveNewValue
// )